//
//  XDSegmentedView.m
//  XDHoHo
//
//  Created by xie yajie on 13-11-12.
//  Copyright (c) 2013年 XD. All rights reserved.
//

#import "XDSegmentedView.h"

#import "UIImage+Category.h"

@interface XDSegmentedView()
{
    id _target;
    SEL _action;
    UIButton    *_preButton;
    int subButtonWith;
    int subButtonHeight;
    int move_X;//移动视图的x坐标
    UIImageView *_moveImageView;//移动视图
    UIImageView *_backgroundImageView;//背景视图
    NSInteger count; //按钮数
    NSMutableArray *badgeViewList;//新消息数视图列表
}
@end

@implementation XDSegmentedView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.selectedIndex = 0;
        self.buttonTitleNormalColor = [UIColor grayColor];
        self.buttonTitleSelectedColor = [UIColor blackColor];
        self.style = XDSegmentedViewStyleCenterMove;
        self.font = [UIFont boldSystemFontOfSize:14.0];
        self.opaque = NO;
        self.clipsToBounds = YES;
        count = 1;
        badgeViewList = [[NSMutableArray alloc] init];
        _subButtonList = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    subButtonHeight = frame.size.height;
}

- (void)setBackgroundImgName:(NSString *)backgroundImgName
{
    _backgroundImgName = backgroundImgName;
    if (_backgroundImgName.length && !_backgroundImageView) {
         _backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        [self addSubview:_backgroundImageView];
        [self sendSubviewToBack:_backgroundImageView];
    }
    UIImage *bg = [[UIImage imageNamed:_backgroundImgName] resizableImageWithCompatibleCapInsets:UIEdgeInsetsMake(0, 0, 3, 0) resizingMode:UIImageResizingModeStretch];
    _backgroundImageView.image = bg;
}
- (void)setButtonTitleDataSource:(NSArray *)buttonTitleDataSource
{
    _buttonTitleDataSource = buttonTitleDataSource;
    if (_buttonTitleDataSource.count > count) {
        count = _buttonTitleDataSource.count;
    }
}
- (void)setButtonNormalImageDataSource:(NSArray *)buttonNormalImageDataSource
{
    _buttonNormalImageDataSource = buttonNormalImageDataSource;
    if (_buttonNormalImageDataSource.count > count) {
        count = _buttonNormalImageDataSource.count;
    }
}
- (void)setButtonSelectedImageDataSource:(NSArray *)buttonSelectedImageDataSource
{
    _buttonSelectedImageDataSource = buttonSelectedImageDataSource;
    if (_buttonSelectedImageDataSource.count > count) {
        count = _buttonSelectedImageDataSource.count;
    }
}
- (void)setMoveImgName:(NSString *)moveImgName
{
    _moveImgName = moveImgName;
    if (_moveImgName != nil && _moveImageView == nil) {
        _moveImageView = [[UIImageView alloc] init];
        [self addSubview:_moveImageView];
    }
    _moveImageView.image = [UIImage imageNamed:_moveImgName];
}

- (void)createSubButton
{
    //按钮宽度
    subButtonWith = self.frame.size.width / count;
    //按钮
    for (int i = 0; i < count; i++) {
        float x = i * subButtonWith;
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, 0, subButtonWith, subButtonHeight)];
        button.backgroundColor = [UIColor clearColor];
        button.tag = i;
        button.titleLabel.font = _font;
        NSString *title = [self getButtonTilteWithIndex:i];
        [button setTitle:title forState:UIControlStateNormal];
        button.titleLabel.contentMode = UIControlContentHorizontalAlignmentCenter;
        UIImage *normalImage = [self getButtonNormalImageWithIndex:i];
        if (normalImage) {
            button.imageView.contentMode = UIViewContentModeScaleAspectFit;
            button.imageEdgeInsets = UIEdgeInsetsMake(4.0, 0.0, 6.0, 0.0);
            button.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        }
        
        CGSize contentSize = [title sizeWithFont:_font constrainedToSize:CGSizeMake(subButtonWith, subButtonHeight) lineBreakMode:UILineBreakModeCharacterWrap];
        
        if (i == _selectedIndex) {//默认选中项
            _preButton = button;
            UIImage *selectedImage = [self getButtonSelectedImageWithIndex:i];
            [_preButton setTitleColor:_buttonTitleSelectedColor forState:UIControlStateNormal];
            [_preButton setImage:selectedImage forState:UIControlStateNormal];
            
            float moveImageViewWidth = contentSize.width + 20;
            int moveImageViewX = _selectedIndex * subButtonWith + (subButtonWith - moveImageViewWidth) /2;
            if (selectedImage) {//只有图片
                moveImageViewWidth = button.imageView.frame.size.width;
                moveImageViewX = _selectedIndex * subButtonWith + (subButtonWith - moveImageViewWidth) /2;
            }
            if (selectedImage && title) {//有图片 有文字
                moveImageViewWidth = contentSize.width + button.imageView.frame.size.width;
                moveImageViewX = _selectedIndex * subButtonWith + (subButtonWith - moveImageViewWidth) /2 + 3;
            }
                
            if (_style == XDSegmentedViewStyleTopMove) {
                _moveImageView.frame = CGRectMake(moveImageViewX, 4, moveImageViewWidth, subButtonHeight - 4);
            }else if(_style == XDSegmentedViewStyleBottomMove){
                _moveImageView.frame = CGRectMake(moveImageViewX, subButtonHeight - 3, moveImageViewWidth, 3);
            }
            
        }else{
            [button setTitleColor:_buttonTitleNormalColor forState:UIControlStateNormal];
            [button setImage:normalImage forState:UIControlStateNormal];
        }
        
        [button addTarget:self action:@selector(doAction:) forControlEvents:UIControlEventTouchUpInside];
        [_subButtonList addObject:button];
        [self addSubview:button];
    }
}

- (void)setSelectedIndex:(NSInteger)selectedIndex
{
    _selectedIndex = selectedIndex ;
    if (selectedIndex < _subButtonList.count) {
        [self doAction:[_subButtonList objectAtIndex:selectedIndex]];
    }
}

- (void)doAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    int index = button.tag;
    if (!_havaDoubleClick) {
        if (_preButton == button) {
            return;
        }
    }
    //以前选择的按钮还原
    UIImage *normalImage = [self getButtonNormalImageWithIndex:_preButton.tag];
    [_preButton setTitleColor:_buttonTitleNormalColor forState:UIControlStateNormal];
    [_preButton setImage:normalImage forState:UIControlStateNormal];
    //现在选择的按钮选中
    UIImage *selectedImage = [self getButtonSelectedImageWithIndex:index];
    [button setTitleColor:_buttonTitleSelectedColor forState:UIControlStateNormal];
    [button setImage:selectedImage forState:UIControlStateNormal];
    [self move:index]; 

    _preButton = button;
    _selectedIndex = index;
    [_target performSelector:_action withObject:self];
}

- (void)setSelectedButtonStyle:(UIButton *)button
{
    int index = button.tag;
    UIImage *image = nil;
    if (index < _buttonSelectedImageDataSource.count) {
        image = [_buttonSelectedImageDataSource objectAtIndex:index];
    }
    [button setBackgroundImage:image forState:UIControlStateNormal];
    [button setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
}
- (void)setNormalButtonStyle:(UIButton *)button
{
    int index = button.tag;
    UIImage *image = nil;
    if (index < _buttonNormalImageDataSource.count) {
        image = [_buttonNormalImageDataSource objectAtIndex:index];
    }
    [button setBackgroundImage:image forState:UIControlStateNormal];
    [button setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
}

- (void)addTarget:(id)target action:(SEL)action
{
    _target = target;
    _action = action;
}
//移动动画
- (void)move:(int)index
{
    [UIView animateWithDuration:0.2 animations:^{
        CGRect frame = _moveImageView.frame;
        frame.origin.x = index * subButtonWith + (subButtonWith - frame.size.width) /2;
        if ([self getButtonTilteWithIndex:index] && [self getButtonNormalImageWithIndex:index]) {
            frame.origin.x += 3;
        }
        _moveImageView.frame = frame;
    }];
}

//得到指定下标按钮一般图片
- (UIImage *)getButtonNormalImageWithIndex:(NSInteger)index
{
    if (index < _buttonNormalImageDataSource.count) {
        return [_buttonNormalImageDataSource objectAtIndex:index];
    }
    return nil;
}
//得到指定下标按钮选中图片
- (UIImage *)getButtonSelectedImageWithIndex:(NSInteger)index
{
    if (index < _buttonSelectedImageDataSource.count) {
        return [_buttonSelectedImageDataSource objectAtIndex:index];
    }
    return nil;
}
- (NSString *)getButtonTilteWithIndex:(NSInteger)index
{
    if (index < _buttonTitleDataSource.count){
        return [_buttonTitleDataSource objectAtIndex:index];
    }
    return nil;
}

@end
